package org.nch.videoLauncher.util;/**
 * Created by IntelliJ IDEA.
 * User: bill
 * Date: Dec 13, 2008
 * Time: 11:02:57 AM
 * To change this template use File | Settings | File Templates.
 */

import org.apache.commons.httpclient.SimpleHttpConnectionManager;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.Credentials;
import org.apache.commons.httpclient.auth.AuthScope;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.params.HttpConnectionManagerParams;

import java.io.*;
import java.net.Authenticator;
import java.net.URL;
import java.util.ArrayList;

class HttpUtil {

//    static Logger log = Logger.getRootLogger();

    static StringBuffer readDataToStringBuffer(URL url) throws Exception {

        StringBuffer data = null;
        BufferedInputStream stream;

        //long time = System.currentTimeMillis();

        SimpleHttpConnectionManager connectionManager = new SimpleHttpConnectionManager();

        HttpConnectionManagerParams params = connectionManager.getParams();

        //params.setSoTimeout(2000);
        params.setConnectionTimeout(8000);

        connectionManager.setParams(params);

        HttpClient client = new HttpClient(connectionManager);

        setProxySetting(client);

        GetMethod method = new GetMethod(url.toString());
        method.setDoAuthentication(true);

        int statusCode = client.executeMethod(method);

        if (statusCode == HttpStatus.SC_OK) {

            stream = new BufferedInputStream(method.getResponseBodyAsStream());
            int buffer;

            /* Saves the page data in a string buffer... */
            data = new StringBuffer();

            while ((buffer = stream.read()) != -1) {
                data.append((char) buffer);
            }

            stream.close();
        }
        return data;
    }


    static byte[] readDataToByteArray(URL url) throws Exception {

        byte[] data = {-1};

        //long time = System.currentTimeMillis();

        SimpleHttpConnectionManager connectionManager = new SimpleHttpConnectionManager();

        HttpConnectionManagerParams params = connectionManager.getParams();
        params.setConnectionTimeout(2000);
        connectionManager.setParams(params);

        HttpClient client = new HttpClient(connectionManager);
        //HostConfiguration config = new HostConfiguration();
//        setProxySetting(client);

        GetMethod method = new GetMethod(url.toString());
        //method.setDoAuthentication(true);

        try {

            int statusCode = client.executeMethod(method);

            if (statusCode == HttpStatus.SC_OK) {

                BufferedInputStream inputStream = new BufferedInputStream(method.getResponseBodyAsStream());
                ByteArrayOutputStream byteStream = new ByteArrayOutputStream(inputStream.available());

                int buffer;
                while ((buffer = inputStream.read()) != -1)
                    byteStream.write(buffer);

                inputStream.close();
                data = byteStream.toByteArray();
            }

        } catch (Exception e) {
            throw new Exception(e.getMessage());
        } finally {
            method.releaseConnection();
        }

        return data;
    }


    static void setProxySetting(HttpClient client) {





            //HostConfiguration config = client.getHostConfiguration();
            Credentials defaultcreds = null;

            /*Adds proxy settings*/
            java.util.Properties systemSettings = System.getProperties();


                systemSettings.put("proxySet", "true");
                systemSettings.put("socksProxySet", "false");

                /* Removing SOCKS properties */
                systemSettings.remove("socksProxyHost");
                systemSettings.remove("socksProxyPort");

                Authenticator.setDefault(null);


                client.getHostConfiguration().setProxy("home01", Integer.parseInt("3128"));

                client.getState().setProxyCredentials(new AuthScope("home01", Integer.parseInt("3128"), AuthScope.ANY_REALM), defaultcreds);


            /*Saves proxy settings*/
            System.setProperties(systemSettings);

    }


    public static void writeToFile(String fileName, StringBuffer data) {

        try {

            FileOutputStream fileStream = new FileOutputStream(new File(fileName));
            for (int u = 0; u < data.length(); u++)
                fileStream.write(data.charAt(u));
            fileStream.close();

        } catch (Exception e) {
//            log.error("Exception:" + e.getMessage());
            System.out.println(e.getMessage());
        }
    }


    /**
     * Decodes a html string and returns its unicode string.
     */
    protected static String decodeHTML(String toDecode) {
        String decoded = "";

        try {
            int end = 0;
            for (int i = 0; i < toDecode.length(); i++) {
                if (toDecode.charAt(i) == '&' && toDecode.charAt(i + 1) == '#' && (end = toDecode.indexOf(";", i)) != -1) {
                    decoded += (char) Integer.parseInt(toDecode.substring(i + 2, end));
                    i = end;
                } else if (toDecode.charAt(i) == '<' && toDecode.indexOf('>', i) != -1) {
                    i = toDecode.indexOf('>', i);
                } else {
                    decoded += toDecode.charAt(i);
                }
            }

            // replacing html code like &quot; and &amp;
            decoded = decoded.replaceAll("&amp;", "&");
            decoded = decoded.replaceAll("&quot;", "\"");
            decoded = decoded.replaceAll("&nbsp;", " ");

        } catch (Exception e) {
          //  log.error("", e);
            System.out.println(e.getMessage());
        }

        /* Returns the decoded string... */
        return removeDoubleSpace(decoded);
    }


    /**
     * Decodes a html string and returns its unicode string.
     */
    protected static Object[] decodeHTMLtoArray(String toDecode) {
        ArrayList decoded = new ArrayList();
        String tmp = "";

        try {
            int end = 0;
            for (int i = 0; i < toDecode.length(); i++) {
                if (toDecode.charAt(i) == '&' && toDecode.charAt(i + 1) == '#' && (end = toDecode.indexOf(";", i)) != -1) {
                    tmp += (char) Integer.parseInt(toDecode.substring(i + 2, end));
                    i = end;
                } else if (toDecode.charAt(i) == '<' && toDecode.indexOf('>', i) != -1) {
                    i = toDecode.indexOf('>', i);

                    if (!tmp.trim().equals(""))
                        decoded.add(tmp.trim());

                    tmp = "";
                } else {
                    tmp += toDecode.charAt(i);
                }
            }
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
        /* Returns the decoded string... */
        return decoded.toArray();
    }


    /* Creates the URL and sets the appropriate proxy values */
    //protected static URL makeURL(String url) {
    static void setProxySetting2(HttpClient client) {

        //url = makeURL(urlType+title.replaceAll("[\\p{Blank}]+","%20"));

//        MovieManagerConfig mm = MovieManager.getConfig();
        //URL urlData = null;

        try {
//            if (mm.getProxyEnabled()) {

              if (false){
//                String host = mm.getProxyHost();
//                String port = mm.getProxyPort();
//
//                /*Adds proxy settings*/
//                java.util.Properties systemSettings = System.getProperties();
//
//                if (mm.equals("HTTP")) {
//                    systemSettings.put("proxySet", "true");
//                    systemSettings.put("proxyHost", host);
//                    systemSettings.put("proxyPort", port);
//                } else {
//                    systemSettings.put("socksProxySet", "true");
//                    systemSettings.put("socksProxyHost", host);
//                    systemSettings.put("socksProxyPort", port);
//                }
//
//                /*Saves proxy settings*/
//                System.setProperties(systemSettings);
//
//                if (mm.getAuthenticationEnabled()) {
//                    String user = mm.getProxyUser();
//                    String password = mm.getProxyPassword();
//
//                    /*Adds authentication*/
//                    Authenticator.setDefault(new MyAuth(user, password));
//                } else
//                    Authenticator.setDefault(null);/*Removes authentication*/
            } else {
                /*Removes proxy settings*/
                java.util.Properties systemSettings = System.getProperties();
                systemSettings.remove("proxySet");
                systemSettings.remove("proxyHost");
                systemSettings.remove("proxyPort");

                systemSettings.remove("socksProxySet");
                systemSettings.remove("socksProxyHost");
                systemSettings.remove("socksProxyPort");
                System.setProperties(systemSettings);

                /*Removes authentication*/
                Authenticator.setDefault(null);
            }
            //urlData = new URL(url);
        }
        catch (Exception e) {
            System.out.println(e.getMessage());;
        }
    }

    public static String cleanInt(String toBeCleaned, int debugMode) {

        boolean start = false;
        String result = "";

//        if (debugMode == 1)
//            log.debug("toBeCleaned:" + toBeCleaned);

        for (int i = 0; i < toBeCleaned.length(); i++) {

            if (Character.isDigit(toBeCleaned.charAt(i)))
                start = true;

            if (start) {

//                if (debugMode == 1 && toBeCleaned.charAt(i) == ',')
//                    log.debug("NumValComma:"+ Character.getNumericValue(toBeCleaned.charAt(i)));

                if (Character.getNumericValue(toBeCleaned.charAt(i)) != -1 || toBeCleaned.charAt(i) == ',' || toBeCleaned.charAt(i) == '.') {

                    if (Character.isDigit(toBeCleaned.charAt(i))) {
                        result += toBeCleaned.charAt(i);
                    }
                    else {
                        break;
                    }
                }
            }
        }

//        if (debugMode == 1)
//            log.debug("result:" + result);

        return result;
    }

    public static String removeDoubleSpace(String str) {

        /* Remove all double white space */
        StringBuffer stringBuff = new StringBuffer();
        for(int x = 0; x < str.length(); x++)
            if (str.charAt(x) != ' ' || (str.length() != x+1 && str.charAt(x+1) != ' '))
                stringBuff = stringBuff.append(str.charAt(x));

        return stringBuff.toString();
    }



}
